<template><div><h2 id="路由" tabindex="-1"><a class="header-anchor" href="#路由"><span>路由</span></a></h2>
<h2 id="基本路由" tabindex="-1"><a class="header-anchor" href="#基本路由"><span>基本路由</span></a></h2>
<p>前面章节，我们已经知道通过 <code v-pre>/index.php</code> 路由来访问应用入口，这实际是一个缺省的路由，其完整的 URL 应该是 <code v-pre>/index.php?r=</code>，遵循以下的基本路由格式：</p>
<div class="language-bash line-numbers-mode" data-highlighter="prismjs" data-ext="sh" data-title="sh"><pre v-pre class="language-bash"><code><span class="line">/index.php?r<span class="token operator">=</span><span class="token punctuation">{</span>moduleId<span class="token punctuation">}</span>/<span class="token punctuation">{</span>controllerId<span class="token punctuation">}</span>/<span class="token punctuation">{</span>actionId<span class="token punctuation">}</span><span class="token operator">&amp;</span><span class="token assign-left variable">param</span><span class="token operator">=</span>xxx</span>
<span class="line"><span class="token comment"># 或者</span></span>
<span class="line">/index.php?r<span class="token operator">=</span><span class="token punctuation">{</span>controllerId<span class="token punctuation">}</span>/<span class="token punctuation">{</span>actionId<span class="token punctuation">}</span><span class="token operator">&amp;</span><span class="token assign-left variable">param</span><span class="token operator">=</span>xxx</span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>其中这个 <code v-pre>r</code> 就是路由定位参数，告诉我们应该调用某个模块（如果存在）下的某个控制器的某个动作。</p>
<h3 id="隐式路由" tabindex="-1"><a class="header-anchor" href="#隐式路由"><span>隐式路由</span></a></h3>
<p>Yii 框架针对非 RESTful 项目的 普通 web 开发，采用隐式路由的方式，无需提前声明路由，它会根据你创建的模块、控制器和动作，自动匹配 <code v-pre>模块 / 控制器 / 动作</code> 格式的路由参数，例如，在应用主体的 <code v-pre>controllers</code> 目录下创建了一个 <code v-pre>SiteController</code>，具体如下：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>web<span class="token punctuation">\</span>Controller</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token keyword">class</span> <span class="token class-name-definition class-name">SiteController</span> <span class="token keyword">extends</span> <span class="token class-name">Controller</span></span>
<span class="line"><span class="token punctuation">{</span></span>
<span class="line">    <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">actionIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span></span>
<span class="line">    <span class="token punctuation">{</span></span>
<span class="line">        <span class="token keyword">return</span> <span class="token variable">$this</span><span class="token operator">-></span><span class="token function">render</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'index'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line">    <span class="token punctuation">}</span></span>
<span class="line"><span class="token punctuation">}</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>此时就等于隐式定义了一个访问的路由 <code v-pre>/index.php?r=site/index</code>。</p>
<h3 id="默认路由" tabindex="-1"><a class="header-anchor" href="#默认路由"><span>默认路由</span></a></h3>
<p>如果一个请求并没有提供一个具体的路由或者说没有提供路由定位参数 <code v-pre>r</code>，比如，对首页的请求。此时就会启用由 [[yii\web\Application::defaultRoute]] 属性所指定的默认路由。该属性的默认值为 <code v-pre>site/index</code>，它指向 <code v-pre>site</code> 控制器的 <code v-pre>index</code> 动作。你可以在应用配置中调整该属性的值，示例如下：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">return</span> <span class="token punctuation">[</span></span>
<span class="line">    <span class="token comment">// ...</span></span>
<span class="line">    <span class="token string single-quoted-string">'defaultRoute'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'main/index'</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span><span class="token punctuation">;</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><h4 id="模块中默认路由" tabindex="-1"><a class="header-anchor" href="#模块中默认路由"><span>模块中默认路由</span></a></h4>
<p>和应用系统中的默认路由类似，模块中也存在一个默认路由。</p>
<p>例如，如果有一个 <code v-pre>user</code> 模块，当请求到 <code v-pre>user</code> 模块时，模块的 [[yii\base\Module::defaultRoute]] 属性来决定默认的路由，它可以由子模块 ID、控制器 ID 和动作 ID 组成，比如，<code v-pre>help</code>、<code v-pre>post/create</code>、<code v-pre>admin/post/create</code> 等，它的默认值是 <code v-pre>default</code>，仅代表 <code v-pre>DefaultController</code> 控制器，并没有中没有指定任何动作，此时，[[yii\base\Controller::defaultAction]] 属性将决定默认的动作，它的默认值是 <code v-pre>index</code>。</p>
<p>综上所述，在这个例子中的完整的路由，应该如下：</p>
<div class="language-bash line-numbers-mode" data-highlighter="prismjs" data-ext="sh" data-title="sh"><pre v-pre class="language-bash"><code><span class="line">/index.php?r<span class="token operator">=</span>user/default/index</span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div></div></div><h3 id="全局拦截路由" tabindex="-1"><a class="header-anchor" href="#全局拦截路由"><span>全局拦截路由</span></a></h3>
<p>有时候，你会想要将你的 Web 应用，临时调整到维护模式，此时，所有的请求都会显示同一个信息页。当然，要实现这一点有很多种方法。这里面最简单快捷的方法就是在应用配置中设置 [[yii\web\Application::catchAll]] 属性：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">return</span> <span class="token punctuation">[</span></span>
<span class="line">    <span class="token comment">// ...</span></span>
<span class="line">    <span class="token string single-quoted-string">'catchAll'</span> <span class="token operator">=></span> <span class="token punctuation">[</span><span class="token string single-quoted-string">'site/offline'</span><span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span><span class="token punctuation">;</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>根据上面的配置，<code v-pre>site/offline</code> 控制器将被用来处理所有的请求。</p>
<p><code v-pre>catchAll</code> 属性应该配置成一个数组，第一个元素为路由，剩下的元素为键值对格式的 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/structure-controllers.md#action-parameters" target="_blank" rel="noopener noreferrer">动作的参数</a>。</p>
<blockquote>
<p>Info: 如果此属性被设置，开发环境中的 <a href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md" target="_blank" rel="noopener noreferrer">调试工具条</a> 将被停用。</p>
</blockquote>
<h2 id="urlmanager-组件" tabindex="-1"><a class="header-anchor" href="#urlmanager-组件"><span>urlManager 组件</span></a></h2>
<p>在普通的 Web 应用中，路由相关操作，主要包括路由解析和创建 URL，负责这块的组件是 <code v-pre>yii\web\UrlManager</code>，它是 Yii 的核心应用组件，无需在应用配置文件中声明，即可直接调用 <code v-pre>\Yii::$app-&gt;urlManager</code> 来访问，它提供 <code v-pre>parseRequest()</code> 方法来解析请求的 URL 并返回路由信息和参数，它的 <code v-pre>createUrl()</code> 方法用来根据提供的路由和参数创建一个可访问的 URL。</p>
<p>在应用配置中配置 <code v-pre>urlManager</code> 组件，可以让你的应用不改变现有代码的情况下识别或创建任意的 URL格式。</p>
<h3 id="url-格式化" tabindex="-1"><a class="header-anchor" href="#url-格式化"><span>URL 格式化</span></a></h3>
<p><code v-pre>urlManager</code> 组件，主要提供以下两种 URL 格式：</p>
<ul>
<li>
<p>默认 URL 格式：<br>
使用一个参数 <code v-pre>r</code> 表示路由，并且使用一般的参数格式表示请求参数。<br>
例如，<code v-pre>/index.php?r=post/view&amp;id=100</code> 表示路由为 <code v-pre>post/view</code>，参数 <code v-pre>id</code> 为 100。您不需要为 <code v-pre>yii\web\UrlManager</code> 做任何配置，即可在任何 Web 服务器正常使用这个路由。</p>
</li>
<li>
<p>美化 URL 格式：<br>
您也可以在脚本名称后面使用更多的路径信息表示路由和参数信息。<br>
例如，用适当的 [[yii\web\UrlManager::rules]] 属性，将 <code v-pre>/index.php/post/100</code> 中附加的路径信息 <code v-pre>/post/100</code> 表示 路由为 <code v-pre>post/view</code>，参数 <code v-pre>id</code> 为 100。<br>
因此，要使用美化，您需要根据实际的需求配置一组 [[yii\web\UrlManager::rules]] 属性来规定 URL 的样式。您也可以仅设置 [[yii\web\UrlManager::enablePrettyUrl]] 属性，来切换两种 URL 格式，而不必改动任何程序代码。</p>
</li>
</ul>
<p>例如使用下面的代码创建一个到 <code v-pre>post/view</code> 控制器的 URL：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>helpers<span class="token punctuation">\</span>Url</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token variable">$url</span> <span class="token operator">=</span> <span class="token class-name class-name-fully-qualified static-context"><span class="token punctuation">\</span>Yii</span><span class="token operator">::</span><span class="token variable">$app</span><span class="token operator">-></span><span class="token property">urlManager</span><span class="token operator">-></span><span class="token function">createUrl</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/view'</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'id'</span> <span class="token operator">=></span> <span class="token number">100</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 也可以用助手函数</span></span>
<span class="line"><span class="token comment">// Url::to() 将调用 UrlManager::createUrl() 来创建URL</span></span>
<span class="line"><span class="token variable">$url</span> <span class="token operator">=</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/view'</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'id'</span> <span class="token operator">=></span> <span class="token number">100</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>根据 <code v-pre>urlManager</code> 中的配置，创建出来的URL可能看起来像是以下的一种格式（或者其它的格式）。如果此URL被访问，将被解析成原来的路由和参数。</p>
<div class="language-bash line-numbers-mode" data-highlighter="prismjs" data-ext="sh" data-title="sh"><pre v-pre class="language-bash"><code><span class="line">/index.php?r<span class="token operator">=</span>post%2Fview<span class="token operator">&amp;</span><span class="token assign-left variable">id</span><span class="token operator">=</span><span class="token number">100</span></span>
<span class="line">/index.php/post/100</span>
<span class="line">/posts/100</span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><h3 id="路由解析" tabindex="-1"><a class="header-anchor" href="#路由解析"><span>路由解析</span></a></h3>
<p>当 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/structure-entry-scripts.md" target="_blank" rel="noopener noreferrer">入口脚本</a> 在调用 [[yii\web\Application::run()|run()]] 方法时，它进行的第一个操作就是解析输入的请求，然后实例化对应的 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/structure-controllers.md" target="_blank" rel="noopener noreferrer">控制器动作</a> 处理这个请求。该过程就被称为 <a href="https://en.wikipedia.org/wiki/Routing" title="路由解析" target="_blank" rel="noopener noreferrer">路由解析</a>。</p>
<p>路由处理包含两个步骤：</p>
<ul>
<li>请求被解析成一个路由和关联的参数；</li>
<li>路由相关的一个 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/structure-controllers.md#actions" target="_blank" rel="noopener noreferrer">控制器动作</a> 被创建出来处理这个请求。</li>
</ul>
<p>如果使用默认 URL 格式，解析请求到路由只是简单的从 <code v-pre>GET</code> 请求中得到命名为 <code v-pre>r</code> 的参数。</p>
<p>当使用用美化URL格式时，[[yii\web\UrlManager]] 将检查它注册的 <code v-pre>rules</code> 属性，找到一条可以匹配的，并将请求转到路由的规则。如果找不到任何匹配的规则，系统将抛出 404 异常（[[yii\web\NotFoundHttpException]]）。</p>
<p>一旦请求解析成路由，系统将马上根据路由信息创建一个控制器动作。路由信息根据 <code v-pre>/</code> 分解成多个部分。例如，<code v-pre>site/index</code> 将被分解成 <code v-pre>site</code> 和 <code v-pre>index</code> 两部分。每个部分都可能被认为是一个模块、控制器或动作的 ID。从路由的第一个部分开始，系统将执行以下步骤创建所需模块（如果有模块的话）、控制器和动作：</p>
<ol>
<li>设置应用系统作为当前的模块。</li>
<li>检查当前模块中的 [[yii\base\Module::controllerMap]] 属性是否存在当前 ID。如果存在，根据控制器映射中的定义创建一个控制器实例，跳到步骤 5 处理路由剩下的部分。</li>
<li>检查 ID 是否为当前模块下 [[yii\base\Module::modules]] 属性定义的子模块，如果是，创建对应子模块，跳到步骤 2 使用刚创建的子模块处理路由下一部分。</li>
<li>将 ID 作为一个 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/structure-controllers.md#controller-ids" target="_blank" rel="noopener noreferrer">控制器 ID</a> 并创建一个控制器实例，并用来处理路由剩下的部分。</li>
<li>控制器在自己的 [[yii\base\Controller::actions()]] 属性中查找当前ID。如果找到，根据映射中的定义创建一个动作。如果没找到，控制器将尝试根据 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/structure-controllers.md#action-ids" target="_blank" rel="noopener noreferrer">动作ID</a> 定义的动作方法创建一个行内动作。</li>
</ol>
<p>在上面的步骤中，如果出现任何错误，系统将抛出一个 404 异常（[[yii\web\NotFoundHttpException]]），表示路由处理程序出现的错误信息。</p>
<h3 id="创建-url" tabindex="-1"><a class="header-anchor" href="#创建-url"><span>创建 URL</span></a></h3>
<p>与 <strong>路由解析</strong> 相反的操作是将给定的路由和参数生成一个可访问的URL地址，这个操作叫做 <strong>创建 URL</strong>。创建出来的 URL 被请求的时候，路由处理器可以解析成原始的路由信息和参数。</p>
<p>Yii提供了一个助手方法 [[yii\helpers\Url::to()]]，用来根据提供的路由和参数创建各种各样的URL。例如：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>helpers<span class="token punctuation">\</span>Url</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 创建一个普通的路由URL：/index.php?r=post%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 创建一个带路由参数的URL：/index.php?r=post%2Fview&amp;id=100</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/view'</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'id'</span> <span class="token operator">=></span> <span class="token number">100</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 创建一个带锚定的URL：/index.php?r=post%2Fview&amp;id=100#content</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/view'</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'id'</span> <span class="token operator">=></span> <span class="token number">100</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'#'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'content'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 创建一个绝对路径URL：http://www.example.com/index.php?r=post%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token constant boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 创建一个带https协议的绝对路径URL：https://www.example.com/index.php?r=post%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'https'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>注意上面的例子中，我们假定使用默认的 URL 格式。如果启用美化的 URL 格式，创建出来的 URL 根据使用的 [[yii\web\UrlManager::rules]] 属性，可能有所不同。</p>
<h4 id="参数规则" tabindex="-1"><a class="header-anchor" href="#参数规则"><span>参数规则</span></a></h4>
<p>方法 [[yii\helpers\Url::to()]] 传入的路由是上下文相关的。根据以下规则确认传入的路由是一个 <em>相对的</em> 路由还是 <em>绝对的</em> 路由：</p>
<ul>
<li>
<p>如果路由是一个空字符串，则使用当前请求的路由， [[yii\web\Controller::route]]；</p>
</li>
<li>
<p>如果路由中不存在 <code v-pre>/</code>，则被认为是一个当前控制器下的动作 ID，且路由被附加到当前控制器的 [[\yii\web\Controller::uniqueId]] 属性后面；</p>
</li>
<li>
<p>如果路由不以 <code v-pre>/</code> 开头，则被认为是当前模块下的路由，路由将被附加到当前模块的[[\yii\base\Module::uniqueId]] 属性后面。</p>
</li>
<li>
<p>从版本 2.0.2 开始，你可以使用根据 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/concept-aliases.md" target="_blank" rel="noopener noreferrer">别名</a>中定义的别名路由。如果是这种情况，别名将首先被转化为实际的路由，然后根据上面的规则转化成一个绝对路由。</p>
</li>
</ul>
<p>例如，假设当前的模块为 <code v-pre>admin</code>，当前控制器为 <code v-pre>post</code>，</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>helpers<span class="token punctuation">\</span>Url</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 当前请求路由：/index.php?r=admin%2Fpost%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">''</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 只有动作ID的相对路由：/index.php?r=admin%2Fpost%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'index'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 相对路由：/index.php?r=admin%2Fpost%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 绝对路由：/index.php?r=post%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'/post/index'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 假设有一个 "/post/index" 的别名 "@posts"：/index.php?r=post%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'@posts'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>[[yii\helpers\Url::to()]] 方法实际上调用了 [[yii\web\UrlManager]] 中的 <code v-pre>createUrl()</code> 和<code v-pre>createAbsoluteUrl()</code> 方法。下面的介绍中，我们将介绍如何配置 [[yii\web\UrlManager]] 来创建自定义的 URL 格式。</p>
<p>[[yii\helpers\Url::to()]] 方法同时支持创建和任何路由不相关的 URL。这种情况下，第一个参数不再传入一个数组，而是传入一个字符串。例如：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>helpers<span class="token punctuation">\</span>Url</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 当前请求URL：/index.php?r=admin%2Fpost%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 设定了别名的URL：http://example.com</span></span>
<span class="line"><span class="token class-name static-context">Yii</span><span class="token operator">::</span><span class="token function">setAlias</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'@example'</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'http://example.com/'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'@example'</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 绝对URL：http://example.com/images/logo.gif</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">to</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'/images/logo.gif'</span><span class="token punctuation">,</span> <span class="token constant boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>除了 <code v-pre>to()</code> 方法，[[yii\helpers\Url]] 助手类同时提供了多个其它创建 URL 的方法。例如：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>helpers<span class="token punctuation">\</span>Url</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 主页URL：/index.php?r=site%2Findex</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">home</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 根URL，如果程序部署到一个Web目录下的子目录时非常有用</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">base</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 当前请求的权威规范URL</span></span>
<span class="line"><span class="token comment">// 参考 https://en.wikipedia.org/wiki/Canonical_link_element</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">canonical</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token comment">// 记住当前请求的URL并在以后获取</span></span>
<span class="line"><span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">remember</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token keyword">echo</span> <span class="token class-name static-context">Url</span><span class="token operator">::</span><span class="token function">previous</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><h3 id="美化-url" tabindex="-1"><a class="header-anchor" href="#美化-url"><span>美化 URL</span></a></h3>
<p>要使用美化的URL，像下面这样在应用配置中配置 <code v-pre>urlManager</code> 组件：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'components'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'urlManager'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">            <span class="token string single-quoted-string">'enablePrettyUrl'</span> <span class="token operator">=></span> <span class="token constant boolean">true</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'showScriptName'</span> <span class="token operator">=></span> <span class="token constant boolean">false</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'enableStrictParsing'</span> <span class="token operator">=></span> <span class="token constant boolean">false</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'rules'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">                <span class="token comment">// ...</span></span>
<span class="line">            <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>[[yii\web\UrlManager::enablePrettyUrl]] 属性被用来切换是否启用美化URL格式。虽然除了它以外，其它属性都是可选的，但是上面的配置是最常用到的。</p>
<ul>
<li><code v-pre>showScriptName</code>：此属性决定创建的URL中是否包含入口脚本名称。例如，设置为 true 开启后，<code v-pre>/index.php/post/100</code> 将变成 <code v-pre>/post/100</code>。</li>
<li><code v-pre>enableStrictParsing</code>：此属性决定是否开启严格的请求解析。如果设置为启用，请求的URL必须至少匹配 [[yii\web\UrlManager::rules]] 中设定的一条规则作为正确请求，否则系统将抛出 [[yii\web\NotFoundHttpException]] 异常。如果严格解析被关闭，当 [[yii\web\UrlManager::rules]] 中没有任何一条匹配时，请求URL中的路径信息将被作为请求路由使用。</li>
<li><code v-pre>rules</code>：此属性包含一个规则列表，用来规定如何解析和创建URL。这是一个主要属性，你应该根据特定的应用环境配置此属性用来生成特定格式的URL。</li>
</ul>
<blockquote>
<p>Note: 如果你想在URL中隐藏入口脚本名称，除了要设置 <code v-pre>showScriptName</code> 为 false，同时应该配置 Web 服务，处理当请求 URL 没有特殊指定入口脚本时确定要执行哪个PHP文件，如果你使用 Apache Web server，你可以参考 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/start-installation.md#recommended-apache-configuration" target="_blank" rel="noopener noreferrer">安装</a> 中推荐的配置。</p>
</blockquote>
<h4 id="url规则" tabindex="-1"><a class="header-anchor" href="#url规则"><span>URL规则</span></a></h4>
<p>一个URL规则是类 [[yii\web\UrlRule]] 或子类的一个实例。每个URL规则包含一个匹配URL中的路径、路由和少量参数的规则。 如果请求地址匹配一个URL规则，则此规则可以用来解析此请求。 如果生成URL时路由和参数符合一个URL规则，则此规则可以用来生成此URL。</p>
<p>如果开启了美化URL格式，[[yii\web\UrlManager|URL管理器]]使用定义的[[yii\web\UrlManager::rules|规则]]解析请求和创建URL。 尤其注意，[[yii\web\UrlManager|URL管理器]]按照规则中定义的顺序依次检测请求地址， 当找到<em>第一条</em>匹配的规则时停止。 匹配到的规则将被用来解析请求URL到指定的路由和参数。 同样的，创建URL的时候，[[yii\web\UrlManager|URL管理器]] 查找 第一条匹配的的规则并用来生成URL。</p>
<p>你可以配置 [[yii\web\UrlManager::rules]] 为一个数组，键为匹配规则，值为路由。 每条键值对为一条URL规则。例如，下面的 [[yii\web\UrlManager::rules|规则]] 配置了两条URL规则。第一条规则匹配URL <code v-pre>posts</code> 映射到路由 <code v-pre>post/index</code>。 第二条规则匹配符合正则表达式 <code v-pre>post/(\d+)</code> 的URL并映射到路由 <code v-pre>post/view</code>，同时包含 一个参数 <code v-pre>id</code>。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'posts'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'post/&lt;id:\d+>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/view'</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><blockquote>
<p>Info: 规则中的匹配模式用来匹配URL中的路径信息。例如， <code v-pre>/index.php/post/100?source=ad</code> 中的路径信息为 <code v-pre>post/100</code>（开始和结尾处的 <code v-pre>/</code> 将被忽略）和模式 <code v-pre>post/(\d+)</code> 匹配。</p>
</blockquote>
<p>除了定义 URL 规则外，你还可以将规则定义为配置数组。 每个配置数组用来配置一个单独的 URL 规则对象。如果你需要配置 URL 规则的其它参数时可以这样用。 例如：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token comment">// ...其它 URL 规则...</span></span>
<span class="line"></span>
<span class="line">    <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'pattern'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'posts'</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token string single-quoted-string">'route'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token string single-quoted-string">'suffix'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'.json'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>如果你在URL规则中不配置 <code v-pre>class</code> 选项，默认将使用类 [[yii\web\UrlRule]]。</p>
<h4 id="命名参数" tabindex="-1"><a class="header-anchor" href="#命名参数"><span>命名参数</span></a></h4>
<p>一条URL规则可以对匹配模式中的参数设置格式为 <code v-pre>&lt;ParamName:RegExp&gt;</code> 的命名， 其中 <code v-pre>ParamName</code> 指定参数的名称，<code v-pre>RegExp</code> 是可选的用来匹配参数值得正则表达式。 如果没有设置 <code v-pre>RegExp</code>，表示参数值为不包含 <code v-pre>/</code> 的字符串。</p>
<blockquote>
<p>Note: 你可以仅针对参数设置正则表达式，其余部分设置普通文本。</p>
</blockquote>
<p>当一条规则用来匹配URL时，符合匹配规则的相关的参数值被填充到规则中， 并且这些参数可以在 <code v-pre>request</code> 组件中使用 <code v-pre>$_GET</code> 获取到。 当规则用来创建 URL 时， 提供的参数值将被插入到规则定义的指定位置。</p>
<p>让我们使用一些例子来说明命名参数是如何工作的。假设我们定义了以下三条 URL 规则：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'posts/&lt;year:\d{4}>/&lt;category>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'posts'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'post/&lt;id:\d+>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/view'</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>当规则用来解析 URL 时：</p>
<ul>
<li>根据第二条规则，<code v-pre>/index.php/posts</code> 被解析成路由 <code v-pre>post/index</code>；</li>
<li>根据第一条规则，<code v-pre>/index.php/posts/2014/php</code> 被解析成路由 <code v-pre>post/index</code>， 参数 <code v-pre>year</code> 的值是 2014，参数 <code v-pre>category</code> 的值是 <code v-pre>php</code>；</li>
<li>根据第三条规则，<code v-pre>/index.php/post/100</code> 被解析成路由 <code v-pre>post/view</code>， 参数 <code v-pre>id</code> 的值是 100；</li>
<li>当[[yii\web\UrlManager::enableStrictParsing]] 设置为 <code v-pre>true</code> 时，<code v-pre>/index.php/posts/php</code> 将导致一个[[yii\web\NotFoundHttpException]] 异常， 因为无法匹配任何规则。如果 [[yii\web\UrlManager::enableStrictParsing]] 设为 <code v-pre>false</code>（默认值）， 路径部分 <code v-pre>posts/php</code> 将被作为路由。</li>
</ul>
<p>当规则用来生成 URL 时：</p>
<ul>
<li>根据第二条规则 <code v-pre>Url::to(['post/index'])</code> 生成 <code v-pre>/index.php/posts</code>；</li>
<li>根据第一条规则 <code v-pre>Url::to(['post/index', 'year' =&gt; 2014, 'category' =&gt; 'php'])</code> 生成 <code v-pre>/index.php/posts/2014/php</code>；</li>
<li>根据第三条规则 <code v-pre>Url::to(['post/view', 'id' =&gt; 100])</code> 生成 <code v-pre>/index.php/post/100</code>；</li>
<li>根据第三条规则 <code v-pre>Url::to(['post/view', 'id' =&gt; 100, 'source' =&gt; 'ad'])</code> 生成 <code v-pre>/index.php/post/100?source=ad</code>。 因为参数 <code v-pre>source</code> 在规则中没有指定，将被作为普通请求参数附加到生成的 URL 后面。</li>
<li><code v-pre>Url::to(['post/index', 'category' =&gt; 'php'])</code> 生成 <code v-pre>/index.php/post/index?category=php</code>。 注意因为没有任何规则适用，将把路由信息当做路径信息来生成URL， 并且所有参数作为请求查询参数附加到 URL 后面。</li>
</ul>
<h4 id="参数化路由" tabindex="-1"><a class="header-anchor" href="#参数化路由"><span>参数化路由</span></a></h4>
<p>你可以在 URL 规则中嵌入参数名称，这样可以允许一个 URL 规则用来匹配多个路由。 例如，下面的规则在路由中嵌入了 <code v-pre>controller</code> 和 <code v-pre>action</code> 两个参数。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token string single-quoted-string">'rules'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'&lt;controller:(post|comment)>/create'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'&lt;controller>/create'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'&lt;controller:(post|comment)>/&lt;id:\d+>/&lt;action:(update|delete)>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'&lt;controller>/&lt;action>'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'&lt;controller:(post|comment)>/&lt;id:\d+>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'&lt;controller>/view'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'&lt;controller:(post|comment)>s'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'&lt;controller>/index'</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>解析 URL <code v-pre>/index.php/comment/100/update</code> 时，第二条规则适用，设置参数 <code v-pre>controller</code> 为 <code v-pre>comment</code>， 设置参数 <code v-pre>action</code> 为 <code v-pre>update</code>。自然的，路由 <code v-pre>&lt;controller&gt;/&lt;action&gt;</code> 变成了 <code v-pre>comment/update</code>。</p>
<p>同样的，根据路由 <code v-pre>comment/index</code> 创建 URL 时，最后一条规则适用，将生成 URL <code v-pre>/index.php/comments</code>。</p>
<blockquote>
<p>Info: 使用参数化的路由，可以显著的减少 URL 规则的数量， 可以显著提高[[yii\web\UrlManager|URL管理器]]的效率。</p>
</blockquote>
<h4 id="默认参数值" tabindex="-1"><a class="header-anchor" href="#默认参数值"><span>默认参数值</span></a></h4>
<p>默认的，所有规则中定义的参数都是必须的。如果一个请求 URL 不存在其中一个参数， 或者创建URL时没有指定其中一个参数，则无法应用此规则。 如果需要设置某些参数为可选的，必须设置规则的[[yii\web\UrlRule::defaults|默认值]]属性。 此属性中列出的参数将变成可选的且在没有指定时会使用此处设置的默认值。</p>
<p>下面设置的规则中，参数 <code v-pre>page</code> 和 <code v-pre>tag</code> 都是可选的，当没有指定时将分别使用值 1 和空字符串。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token comment">// ...其它规则...</span></span>
<span class="line">    <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'pattern'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'posts/&lt;page:\d+>/&lt;tag>'</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token string single-quoted-string">'route'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token string single-quoted-string">'defaults'</span> <span class="token operator">=></span> <span class="token punctuation">[</span><span class="token string single-quoted-string">'page'</span> <span class="token operator">=></span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">'tag'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">''</span><span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>上面的规则可以用来解析或创建下面的 URL：</p>
<ul>
<li><code v-pre>/index.php/posts</code>：<code v-pre>page</code> 为 1，<code v-pre>tag</code> 为 ‘’。</li>
<li><code v-pre>/index.php/posts/2</code>：<code v-pre>page</code> 为 2，<code v-pre>tag</code> 为 ‘’。</li>
<li><code v-pre>/index.php/posts/2/news</code>：<code v-pre>page</code> 为 2，<code v-pre>tag</code>为 <code v-pre>'news'</code>。</li>
<li><code v-pre>/index.php/posts/news</code>：<code v-pre>page</code> 为 1，<code v-pre>tag</code> 为 <code v-pre>'news'</code>。</li>
</ul>
<p>如果不使用可选参数，你必须创建 4 条规则才可以实现相同的效果。</p>
<blockquote>
<p>Note: 如果 [[yii\web\UrlRule::$pattern|pattern]] 中仅包含可选参数和斜杠， 只有所有参数被忽略时第一个参数才被忽略。</p>
</blockquote>
<h4 id="带服务名称的规则" tabindex="-1"><a class="header-anchor" href="#带服务名称的规则"><span>带服务名称的规则</span></a></h4>
<p>可以在URL规则中设置Web服务的名称，如果你需要使你的应用程序在不同的Web服务名称下表现不同的话。 例如，下面的规则将URL<code v-pre>http://admin.example.com/login</code>解析成路由<code v-pre>admin/user/login</code>， URL<code v-pre>http://www.example.com/login</code>解析成路由<code v-pre>site/login</code>。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'http://admin.example.com/login'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'admin/user/login'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'http://www.example.com/login'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'site/login'</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>你还可以在服务名称中嵌入参数用来动态的提取服务名称。例如，下面的规则 将URL<code v-pre>http://en.example.com/posts</code>解析成路由<code v-pre>post/index</code>且参数<code v-pre>language=en</code>。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'http://&lt;language:\w+>.example.com/posts'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>从版本 2.0.11 开始，你还可以使用不带协议类型的模式来同时匹配 <code v-pre>http</code> 和 <code v-pre>https</code>。 规则语法和上面相比只是忽略掉 <code v-pre>http:</code> 部分，例如：<code v-pre>'//www.example.com/login' =&gt; 'site/login'</code>。</p>
<blockquote>
<p>Note: 带服务名称的规则<strong>不应该</strong>包含任何子目录。例如，如果程序入口脚本在 <code v-pre>http://www.example.com/sandbox/blog/index.php</code>， 应该使用 <code v-pre>http://www.example.com/posts</code> 代替 <code v-pre>http://www.example.com/sandbox/blog/posts</code>。 这样才可以将你的应用部署到任何目录而不需要更改 URL 规则。Yii 将会自动的检测应用程序所在的根目录。</p>
</blockquote>
<h4 id="url-后缀" tabindex="-1"><a class="header-anchor" href="#url-后缀"><span>URL 后缀</span></a></h4>
<p>你可能因为各种目的需要在 URL 后面添加后缀。例如，你可以在URL后面添加 <code v-pre>.html</code> 让其看起来像是一个 HTML 页面； 也可以添加 <code v-pre>.json</code> 用来表明需要的返回值内容类型。 可以参考下面的系统配置， 通过设置 [[yii\web\UrlManager::suffix]] 属性来达到此目的:</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'components'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'urlManager'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">            <span class="token string single-quoted-string">'enablePrettyUrl'</span> <span class="token operator">=></span> <span class="token constant boolean">true</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'showScriptName'</span> <span class="token operator">=></span> <span class="token constant boolean">false</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'enableStrictParsing'</span> <span class="token operator">=></span> <span class="token constant boolean">true</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'suffix'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'.html'</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'rules'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">                <span class="token comment">// ...</span></span>
<span class="line">            <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>上面的配置允许[[yii\web\UrlManager|URL管理器]]识别或生成带 <code v-pre>.html</code> 后缀的 URL。</p>
<blockquote>
<p>Tip: 你可以设置URL后缀为 <code v-pre>/</code> 让所有的 URL 以斜线结束。</p>
</blockquote>
<blockquote>
<p>Note: 当你配置 URL 后缀时，如果请求的 URL 没有此后缀，系统将认为此 URL 无法识别。 这是 SEO（搜索引擎优化）的最佳实践。</p>
</blockquote>
<p>有时你可能需要在不同的URL使用不同的后缀。可以通过在不同的URL规则下不同的设置[[yii\web\UrlRule::suffix|后缀]]属性。 URL规则中此属性将覆盖在[[yii\web\UrlManager|URL管理器]]中设置的值。 例如，下面的配置中全局使用 <code v-pre>.html</code> 后缀，但是定义了一个自定义的使用 <code v-pre>.json</code> 为后缀的规则。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'components'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'urlManager'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">            <span class="token string single-quoted-string">'enablePrettyUrl'</span> <span class="token operator">=></span> <span class="token constant boolean">true</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token comment">// ...</span></span>
<span class="line">            <span class="token string single-quoted-string">'suffix'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'.html'</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'rules'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">                <span class="token comment">// ...</span></span>
<span class="line">                <span class="token punctuation">[</span></span>
<span class="line">                    <span class="token string single-quoted-string">'pattern'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'posts'</span><span class="token punctuation">,</span></span>
<span class="line">                    <span class="token string single-quoted-string">'route'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line">                    <span class="token string single-quoted-string">'suffix'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'.json'</span><span class="token punctuation">,</span></span>
<span class="line">                <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><h4 id="http-方法" tabindex="-1"><a class="header-anchor" href="#http-方法"><span>HTTP 方法</span></a></h4>
<p>当使用 RESTful 接口时，经常需要根据 HTTP 请求方法将同样的URL解析到不同的路由。可以容易的通过将支持的 HTTP 方法设置为 URL 规则的前缀来实现这个目的。如果一个规则需要支持多种 HTTP 方法，可以将方法名称用逗号隔开。例如，下面的规则有相同的模式 <code v-pre>post/&lt;id:\d+&gt;</code> 但是支持不同的 HTTP 方法。一个 <code v-pre>PUT post/100</code> 请求将被解析到 <code v-pre>post/update</code>，<code v-pre>GET post/100</code> 请求将被解析到 <code v-pre>post/view</code>。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token string single-quoted-string">'rules'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'PUT,POST post/&lt;id:\d+>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/update'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'DELETE post/&lt;id:\d+>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/delete'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'post/&lt;id:\d+>'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/view'</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><blockquote>
<p>Note: 如果一个 URL 规则包含 HTTP 方法，这个规则将只能用来解析请求，除非 <code v-pre>GET</code> 请求明确被指定在 HTTP 方法中， 否则创建 URL 时此规则将被[[yii\web\UrlManager|URL管理器]]忽略。</p>
</blockquote>
<blockquote>
<p>Tip: 为了简化 RESTful 接口的路由定义，Yii 提供了一个特殊的URL规则类 [[yii\rest\UrlRule]] 支持高效的且支持一些设想中的功能，像自动多元化控制器 ID。 更多信息，请参考 RESTful 接口说明中的 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/rest-routing.md" target="_blank" rel="noopener noreferrer">路由</a>章节。</p>
</blockquote>
<h4 id="动态添加规则" tabindex="-1"><a class="header-anchor" href="#动态添加规则"><span>动态添加规则</span></a></h4>
<p>URL规则可以动态添加到[[yii\web\UrlManager|URL管理器]]。如果<a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/structure-modules.md" target="_blank" rel="noopener noreferrer">模块</a>需要管理自己的URL规则时很有必要。 如果需要使路由处理过程中动态添加的规则可用， 你应该在应用程序<a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/runtime-bootstrapping.md" target="_blank" rel="noopener noreferrer">启动引导</a>时添加。 对模块来说，需要实现 [[yii\base\BootstrapInterface]] 接口的 [[yii\base\BootstrapInterface::bootstrap()|bootstrap()]] 方法， 类似下面这样动态添加规则：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">bootstrap</span><span class="token punctuation">(</span><span class="token variable">$app</span><span class="token punctuation">)</span></span>
<span class="line"><span class="token punctuation">{</span></span>
<span class="line">    <span class="token variable">$app</span><span class="token operator">-></span><span class="token function">getUrlManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">-></span><span class="token function">addRules</span><span class="token punctuation">(</span><span class="token punctuation">[</span></span>
<span class="line">        <span class="token comment">// 规则在这里定义</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token constant boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token punctuation">}</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>注意你需要同时在 [[yii\web\Application::bootstrap]] 中指定这些模块，这样模块才可以参与到 <a href="https://github.com/yiisoft/yii2/blob/2.0.44/docs/guide-zh-CN/runtime-bootstrapping.md" target="_blank" rel="noopener noreferrer">启动引导</a>过程中。</p>
<h4 id="自定义-url-规则类" tabindex="-1"><a class="header-anchor" href="#自定义-url-规则类"><span>自定义 URL 规则类</span></a></h4>
<p>尽管默认的 [[yii\web\UrlRule]] 类已经足够灵活可以处理大部分项目了， 有时还是会需要创建一个自定义的规则类。例如，在一个汽车经销网站，你可能会需要使用 这样的URL格式 <code v-pre>/Manufacturer/Model</code>，<code v-pre>Manufacturer</code> 和 <code v-pre>Model</code> 必须同时匹配保存在数据库中的一些数据。 默认的规则类只能使用静态定义而无法适应此种情况。</p>
<p>我们可以创建一个自定义的 URL 规则类来解决这个问题。</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token php language-php"><span class="token delimiter important">&lt;?php</span></span>
<span class="line"></span>
<span class="line"><span class="token keyword">namespace</span> <span class="token package">app<span class="token punctuation">\</span>components</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>web<span class="token punctuation">\</span>UrlRuleInterface</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>base<span class="token punctuation">\</span>BaseObject</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token keyword">class</span> <span class="token class-name-definition class-name">CarUrlRule</span> <span class="token keyword">extends</span> <span class="token class-name">BaseObject</span> <span class="token keyword">implements</span> <span class="token class-name">UrlRuleInterface</span></span>
<span class="line"><span class="token punctuation">{</span></span>
<span class="line">    <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">createUrl</span><span class="token punctuation">(</span><span class="token variable">$manager</span><span class="token punctuation">,</span> <span class="token variable">$route</span><span class="token punctuation">,</span> <span class="token variable">$params</span><span class="token punctuation">)</span></span>
<span class="line">    <span class="token punctuation">{</span></span>
<span class="line">        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token variable">$route</span> <span class="token operator">===</span> <span class="token string single-quoted-string">'car/index'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span></span>
<span class="line">            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">isset</span><span class="token punctuation">(</span><span class="token variable">$params</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'manufacturer'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token variable">$params</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'model'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span></span>
<span class="line">                <span class="token keyword">return</span> <span class="token variable">$params</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'manufacturer'</span><span class="token punctuation">]</span> <span class="token operator">.</span> <span class="token string single-quoted-string">'/'</span> <span class="token operator">.</span> <span class="token variable">$params</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'model'</span><span class="token punctuation">]</span><span class="token punctuation">;</span></span>
<span class="line">            <span class="token punctuation">}</span> <span class="token keyword">elseif</span> <span class="token punctuation">(</span><span class="token keyword">isset</span><span class="token punctuation">(</span><span class="token variable">$params</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'manufacturer'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span></span>
<span class="line">                <span class="token keyword">return</span> <span class="token variable">$params</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'manufacturer'</span><span class="token punctuation">]</span><span class="token punctuation">;</span></span>
<span class="line">            <span class="token punctuation">}</span></span>
<span class="line">        <span class="token punctuation">}</span></span>
<span class="line">        <span class="token keyword">return</span> <span class="token constant boolean">false</span><span class="token punctuation">;</span> <span class="token comment">// this rule does not apply</span></span>
<span class="line">    <span class="token punctuation">}</span></span>
<span class="line"></span>
<span class="line">    <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">parseRequest</span><span class="token punctuation">(</span><span class="token variable">$manager</span><span class="token punctuation">,</span> <span class="token variable">$request</span><span class="token punctuation">)</span></span>
<span class="line">    <span class="token punctuation">{</span></span>
<span class="line">        <span class="token variable">$pathInfo</span> <span class="token operator">=</span> <span class="token variable">$request</span><span class="token operator">-></span><span class="token function">getPathInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line">        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">preg_match</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'%^(\w+)(/(\w+))?$%'</span><span class="token punctuation">,</span> <span class="token variable">$pathInfo</span><span class="token punctuation">,</span> <span class="token variable">$matches</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span></span>
<span class="line">            <span class="token comment">// 检查 $matches[1] 和 $matches[3]</span></span>
<span class="line">            <span class="token comment">// 确认是否匹配到一个数据库中保存的厂家和型号。</span></span>
<span class="line">            <span class="token comment">// 如果匹配，设置参数 $params['manufacturer'] 和 / 或 $params['model']</span></span>
<span class="line">            <span class="token comment">// 返回 ['car/index', $params]</span></span>
<span class="line">        <span class="token punctuation">}</span></span>
<span class="line">        <span class="token keyword">return</span> <span class="token constant boolean">false</span><span class="token punctuation">;</span> <span class="token comment">// 本规则不会起作用</span></span>
<span class="line">    <span class="token punctuation">}</span></span>
<span class="line"><span class="token punctuation">}</span></span>
<span class="line"></span></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>在 [[yii\web\UrlManager::rules]] 配置中设置新定义的规则类：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token string single-quoted-string">'rules'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">    <span class="token comment">// ...其它规则...</span></span>
<span class="line">    <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'class'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'app\components\CarUrlRule'</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token comment">// ...配置其它参数...</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><h2 id="url规范化" tabindex="-1"><a class="header-anchor" href="#url规范化"><span>URL规范化</span></a></h2>
<p>从 2.0.10 版开始 [[yii\web\UrlManager]] 可以配置用 [[yii\web\UrlNormalizer]] URL规范器来处理 相同URL的不同格式，例如是否带结束斜线。因为技术上来说 <code v-pre>http://example.com/path</code> 和 <code v-pre>http://example.com/path/</code> 是完全不同的 URL，两个地址返回相同的内容会导致SEO排名降低。默认情况下 URL 规范器会合并连续的斜线，根据配置决定是否添加或删除结尾斜线，并且会使用 <a href="https://en.wikipedia.org/wiki/HTTP_301" target="_blank" rel="noopener noreferrer">永久重定向</a> 将地址重新跳转到规范化后的URL。URL规范器可以针对URL管理器全局配置，也可以针对规则单独配置 - 默认每个规则都使用URL管理器中的规范器。你可以针对特定的URL规则设置 [[yii\web\UrlRule::$normalizer|UrlRule::$normalizer]] 为 <code v-pre>false</code> 来关闭规范化。</p>
<p>下面的例子显示了一个 [[yii\web\UrlNormalizer]] URL规范器的配置：</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token string single-quoted-string">'urlManager'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">    <span class="token string single-quoted-string">'enablePrettyUrl'</span> <span class="token operator">=></span> <span class="token constant boolean">true</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'showScriptName'</span> <span class="token operator">=></span> <span class="token constant boolean">false</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'enableStrictParsing'</span> <span class="token operator">=></span> <span class="token constant boolean">true</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'suffix'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'.html'</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'normalizer'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'class'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'yii\web\UrlNormalizer'</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token comment">// 调试时使用临时跳转代替永久跳转</span></span>
<span class="line">        <span class="token string single-quoted-string">'action'</span> <span class="token operator">=></span> <span class="token class-name static-context">UrlNormalizer</span><span class="token operator">::</span><span class="token constant">ACTION_REDIRECT_TEMPORARY</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token string single-quoted-string">'rules'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">        <span class="token comment">// ...其它规则...</span></span>
<span class="line">        <span class="token punctuation">[</span></span>
<span class="line">            <span class="token string single-quoted-string">'pattern'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'posts'</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'route'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'post/index'</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'suffix'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'/'</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'normalizer'</span> <span class="token operator">=></span> <span class="token constant boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// 针对此规则关闭规范器</span></span>
<span class="line">        <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token punctuation">[</span></span>
<span class="line">            <span class="token string single-quoted-string">'pattern'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'tags'</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'route'</span> <span class="token operator">=></span> <span class="token string single-quoted-string">'tag/index'</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token string single-quoted-string">'normalizer'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">                <span class="token comment">// 针对此规则不合并连续的斜线</span></span>
<span class="line">                <span class="token string single-quoted-string">'collapseSlashes'</span> <span class="token operator">=></span> <span class="token constant boolean">false</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line"><span class="token punctuation">]</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><blockquote>
<p>Note: 默认 [[yii\web\UrlManager::$normalizer|UrlManager::$normalizer]] 规范器是关闭的。你需要明确配置其开启 来启用 URL 规范化。</p>
</blockquote>
<h2 id="性能优化" tabindex="-1"><a class="header-anchor" href="#性能优化"><span>性能优化</span></a></h2>
<p>在开发复杂的 Web 应用程序时，优化 URL 规则非常重要，以便解析请求和创建 URL 所需 的时间更少。</p>
<p>通过使用参数化路由，您可以减少 URL 规则的数量，这可以显著提高性能。</p>
<p>当解析或创建URL时，[[yii\web\UrlManager|URL manager]] 按照它们声明的顺序检查 URL 规则。 因此，您可以考虑调整 URL 规则的顺序，以便在较少使用的规则之前放置更具体和/或更常用的规则。</p>
<p>如果多个 URL 规则使用相同的前缀，你可以考虑使用 [[yii\web\GroupUrlRule]]， 这样作为一个组合，[[yii\web\UrlManager|URL管理器]]会更高效。 特别是当应用程序由模块组合而成时，每个模块都有各自的 URL 规则且都有各自的模块 ID 作为前缀。</p>
<blockquote>
<p>💖喜欢本文档的，欢迎点赞、收藏、留言或转发，谢谢支持！<br>
作者邮箱：zhuzixian520@126.com，github地址：<a href="https://github.com/zhuzixian520" target="_blank" rel="noopener noreferrer">github.com/zhuzixian520</a></p>
</blockquote>
</div></template>


